<template>
  <div class="inventory-report">
    <!-- 页面标题和操作栏 -->
    <div class="report-header">
      <h2>库存报表</h2>
      <div class="header-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        />
        <el-select v-model="warehouseId" placeholder="选择仓库" style="width: 150px; margin-left: 10px;">
          <el-option label="全部仓库" value="" />
          <el-option label="主仓库" value="1" />
          <el-option label="分仓库A" value="2" />
          <el-option label="分仓库B" value="3" />
        </el-select>
        <el-select v-model="categoryId" placeholder="产品类别" style="width: 150px; margin-left: 10px;">
          <el-option label="全部类别" value="" />
          <el-option label="电子产品" value="1" />
          <el-option label="办公用品" value="2" />
          <el-option label="家具用品" value="3" />
        </el-select>
        <el-button type="primary" @click="refreshData" style="margin-left: 10px;">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <el-dropdown style="margin-left: 10px;">
          <el-button type="success">
            导出 <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="exportExcel">导出Excel</el-dropdown-item>
              <el-dropdown-item @click="exportPDF">导出PDF</el-dropdown-item>
              <el-dropdown-item @click="exportImage">导出图片</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button @click="printReport" style="margin-left: 10px;">
          <el-icon><Printer /></el-icon>
          打印
        </el-button>
      </div>
    </div>

    <!-- 库存关键指标 -->
    <el-row :gutter="20" class="metrics-cards">
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-content">
            <div class="metric-value">¥{{ formatNumber(totalInventoryValue) }}</div>
            <div class="metric-label">库存总价值</div>
            <div class="metric-change positive">+5.8%</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-content">
            <div class="metric-value">{{ totalSKU }}</div>
            <div class="metric-label">SKU数量</div>
            <div class="metric-change positive">+12</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-content">
            <div class="metric-value">{{ turnoverRate }}天</div>
            <div class="metric-label">平均周转天数</div>
            <div class="metric-change negative">+3天</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-content">
            <div class="metric-value">{{ lowStockCount }}</div>
            <div class="metric-label">低库存预警</div>
            <div class="metric-change warning">需关注</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-section">
      <!-- 库存趋势图 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>库存价值趋势</span>
          </template>
          <div ref="inventoryTrendChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      
      <!-- 库存分布 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>库存分布分析</span>
          </template>
          <div ref="inventoryDistributionChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-section">
      <!-- ABC分析 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>ABC分析</span>
          </template>
          <div ref="abcAnalysisChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      
      <!-- 库存周转分析 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>库存周转分析</span>
          </template>
          <div ref="turnoverAnalysisChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 库存预警 -->
    <el-row :gutter="20" class="warning-section">
      <el-col :span="8">
        <el-card>
          <template #header>
            <span style="color: #F56C6C;">低库存预警</span>
          </template>
          <div class="warning-list">
            <div v-for="item in lowStockItems" :key="item.id" class="warning-item">
              <div class="item-info">
                <div class="item-name">{{ item.name }}</div>
                <div class="item-detail">当前库存: {{ item.currentStock }} | 安全库存: {{ item.safeStock }}</div>
              </div>
              <el-tag type="danger" size="small">紧急</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card>
          <template #header>
            <span style="color: #E6A23C;">滞销商品</span>
          </template>
          <div class="warning-list">
            <div v-for="item in slowMovingItems" :key="item.id" class="warning-item">
              <div class="item-info">
                <div class="item-name">{{ item.name }}</div>
                <div class="item-detail">库存天数: {{ item.daysInStock }}天 | 库存量: {{ item.stock }}</div>
              </div>
              <el-tag type="warning" size="small">关注</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card>
          <template #header>
            <span style="color: #909399;">过期预警</span>
          </template>
          <div class="warning-list">
            <div v-for="item in expiringItems" :key="item.id" class="warning-item">
              <div class="item-info">
                <div class="item-name">{{ item.name }}</div>
                <div class="item-detail">过期日期: {{ item.expiryDate }} | 库存: {{ item.stock }}</div>
              </div>
              <el-tag type="info" size="small">提醒</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 库存明细表格 -->
    <el-card class="data-table-card">
      <template #header>
        <span>库存明细</span>
      </template>
      <el-table :data="inventoryDetailData" stripe style="width: 100%">
        <el-table-column prop="productCode" label="产品编码" width="120" />
        <el-table-column prop="productName" label="产品名称" width="200" />
        <el-table-column prop="category" label="类别" width="120" />
        <el-table-column prop="warehouse" label="仓库" width="120" />
        <el-table-column prop="currentStock" label="当前库存" width="100" />
        <el-table-column prop="safeStock" label="安全库存" width="100" />
        <el-table-column prop="unitPrice" label="单价" width="100">
          <template #default="scope">
            ¥{{ scope.row.unitPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="totalValue" label="库存价值" width="120">
          <template #default="scope">
            ¥{{ scope.row.totalValue }}
          </template>
        </el-table-column>
        <el-table-column prop="lastInDate" label="最后入库" width="120" />
        <el-table-column prop="lastOutDate" label="最后出库" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalRecords"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, ArrowDown, Printer } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 响应式数据
const dateRange = ref<[string, string]>(['2024-01-01', '2024-12-31'])
const warehouseId = ref('')
const categoryId = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const totalRecords = ref(200)

// 库存关键指标
const totalInventoryValue = ref(3250000)
const totalSKU = ref(1580)
const turnoverRate = ref(45)
const lowStockCount = ref(23)

// 图表引用
const inventoryTrendChart = ref()
const inventoryDistributionChart = ref()
const abcAnalysisChart = ref()
const turnoverAnalysisChart = ref()

// 预警数据
const lowStockItems = ref([
  { id: 1, name: '笔记本电脑A型', currentStock: 5, safeStock: 20 },
  { id: 2, name: '打印机B型', currentStock: 2, safeStock: 10 },
  { id: 3, name: '办公椅C型', currentStock: 8, safeStock: 15 }
])

const slowMovingItems = ref([
  { id: 1, name: '传真机D型', daysInStock: 180, stock: 25 },
  { id: 2, name: '投影仪E型', daysInStock: 150, stock: 12 },
  { id: 3, name: '扫描仪F型', daysInStock: 120, stock: 18 }
])

const expiringItems = ref([
  { id: 1, name: '墨盒G型', expiryDate: '2024-03-15', stock: 30 },
  { id: 2, name: '硒鼓H型', expiryDate: '2024-04-20', stock: 15 },
  { id: 3, name: '纸张I型', expiryDate: '2024-05-10', stock: 50 }
])

// 库存明细数据
const inventoryDetailData = ref([
  {
    productCode: 'P001',
    productName: '笔记本电脑',
    category: '电子产品',
    warehouse: '主仓库',
    currentStock: 150,
    safeStock: 50,
    unitPrice: 5500,
    totalValue: 825000,
    lastInDate: '2024-01-15',
    lastOutDate: '2024-01-20',
    status: '正常'
  },
  {
    productCode: 'P002',
    productName: '办公桌',
    category: '家具用品',
    warehouse: '分仓库A',
    currentStock: 25,
    safeStock: 30,
    unitPrice: 800,
    totalValue: 20000,
    lastInDate: '2024-01-10',
    lastOutDate: '2024-01-18',
    status: '低库存'
  },
  {
    productCode: 'P003',
    productName: '打印机',
    category: '电子产品',
    warehouse: '主仓库',
    currentStock: 80,
    safeStock: 20,
    unitPrice: 2200,
    totalValue: 176000,
    lastInDate: '2024-01-12',
    lastOutDate: '2024-01-22',
    status: '正常'
  }
])

// 方法
const formatNumber = (num: number) => {
  return num.toLocaleString()
}

const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    '正常': 'success',
    '低库存': 'warning',
    '缺货': 'danger',
    '滞销': 'info'
  }
  return statusMap[status] || 'info'
}

const handleDateChange = () => {
  refreshData()
}

const refreshData = () => {
  ElMessage.success('数据已刷新')
}

const exportExcel = () => {
  ElMessage.success('Excel导出功能开发中')
}

const exportPDF = () => {
  ElMessage.success('PDF导出功能开发中')
}

const exportImage = () => {
  ElMessage.success('图片导出功能开发中')
}

const printReport = () => {
  window.print()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 初始化图表
const initCharts = () => {
  // 库存趋势图
  const inventoryTrend = echarts.init(inventoryTrendChart.value)
  inventoryTrend.setOption({
    title: {
      text: '月度库存价值趋势',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: ¥{c}万'
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value',
      name: '库存价值(万元)'
    },
    series: [{
      data: [320, 315, 325, 330, 310, 340, 335, 345, 350, 355, 325, 330],
      type: 'line',
      smooth: true,
      itemStyle: { color: '#409EFF' },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(64, 158, 255, 0.3)'
          }, {
            offset: 1, color: 'rgba(64, 158, 255, 0.1)'
          }]
        }
      }
    }]
  })

  // 库存分布
  const inventoryDistribution = echarts.init(inventoryDistributionChart.value)
  inventoryDistribution.setOption({
    title: {
      text: '仓库库存分布',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    series: [{
      name: '库存分布',
      type: 'pie',
      radius: '60%',
      data: [
        { value: 1800, name: '主仓库' },
        { value: 800, name: '分仓库A' },
        { value: 650, name: '分仓库B' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  })

  // ABC分析
  const abcAnalysis = echarts.init(abcAnalysisChart.value)
  abcAnalysis.setOption({
    title: {
      text: 'ABC分析',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}% ({d}%)'
    },
    series: [{
      name: 'ABC分析',
      type: 'pie',
      radius: ['40%', '70%'],
      data: [
        { value: 80, name: 'A类商品(80%价值)', itemStyle: { color: '#67C23A' } },
        { value: 15, name: 'B类商品(15%价值)', itemStyle: { color: '#E6A23C' } },
        { value: 5, name: 'C类商品(5%价值)', itemStyle: { color: '#F56C6C' } }
      ],
      label: {
        show: true,
        formatter: '{b}: {c}%'
      }
    }]
  })

  // 库存周转分析
  const turnoverAnalysis = echarts.init(turnoverAnalysisChart.value)
  turnoverAnalysis.setOption({
    title: {
      text: '产品类别周转天数',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: '{b}: {c}天'
    },
    xAxis: {
      type: 'category',
      data: ['电子产品', '办公用品', '家具用品', '其他']
    },
    yAxis: {
      type: 'value',
      name: '周转天数'
    },
    series: [{
      type: 'bar',
      data: [
        { value: 30, itemStyle: { color: '#67C23A' } },
        { value: 45, itemStyle: { color: '#409EFF' } },
        { value: 60, itemStyle: { color: '#E6A23C' } },
        { value: 75, itemStyle: { color: '#F56C6C' } }
      ]
    }]
  })
}

onMounted(() => {
  nextTick(() => {
    initCharts()
  })
})
</script>

<style scoped>
.inventory-report {
  padding: 20px;
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.report-header h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
}

.metrics-cards {
  margin-bottom: 20px;
}

.metric-card {
  text-align: center;
}

.metric-content {
  padding: 10px;
}

.metric-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.metric-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.metric-change {
  font-size: 12px;
  font-weight: bold;
}

.metric-change.positive {
  color: #67C23A;
}

.metric-change.negative {
  color: #F56C6C;
}

.metric-change.warning {
  color: #E6A23C;
}

.charts-section {
  margin-bottom: 20px;
}

.warning-section {
  margin-bottom: 20px;
}

.warning-list {
  max-height: 200px;
  overflow-y: auto;
}

.warning-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f5f7fa;
}

.warning-item:last-child {
  border-bottom: none;
}

.item-info {
  flex: 1;
}

.item-name {
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.item-detail {
  font-size: 12px;
  color: #909399;
}

.data-table-card {
  margin-top: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

@media (max-width: 768px) {
  .report-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    margin-top: 10px;
    flex-wrap: wrap;
  }
  
  .metrics-cards .el-col {
    margin-bottom: 10px;
  }
  
  .warning-section .el-col {
    margin-bottom: 20px;
  }
}
</style>